import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import '../css/temp-chart.css';
import { convertX, convertY, convertSize } from '../utils/responsive';

interface TempChartProps {
  /** ECharts配置项 */
  option: EChartsOption;
  /** 图表主题 */
  theme?: 'light' | 'dark';
  /** 是否启用响应式调整 */
  responsive?: boolean;
}

/**
 * 通用图表组件，自适应父容器大小
 * 只需传入ECharts配置项即可渲染图表
 */
const TempChart: React.FC<TempChartProps> = ({
  option,
  theme = 'light',
  responsive = true
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  // 初始化图表
  useEffect(() => {
    if (!chartRef.current) return;

    // 创建ECharts实例
    chartInstance.current = echarts.init(chartRef.current, theme);

    // 设置图表配置
    chartInstance.current.setOption(option);

    // 清理函数
    return () => {
      chartInstance.current?.dispose();
      chartInstance.current = null;
    };
  }, [option, theme]);

  // 响应式调整
  useEffect(() => {
    if (!responsive || !chartInstance.current) return;

    const handleResize = () => {
      chartInstance.current?.resize();
    };

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);

    // 初始调整一次
    handleResize();

    // 清理事件监听
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [responsive]);

  return (
    <div
      ref={chartRef}
      className="temp-chart"
      style={{
        position: 'absolute',
        left: convertX(22),
        top: convertY(55),
        width: convertSize(360),
        height: convertSize(300, false)
      }}
    />
  );
};

export default TempChart;